<?php

namespace app\model;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class RoomUser extends Model
{
    protected $table = 'room_users';
    
    const STATUS_ACTIVE = 'active';
    const STATUS_LEFT = 'left';
    const STATUS_FINISHED = 'finished';
    
    public $timestamps = false;
    
    protected $fillable = [
        'room_id',
        'user_id',
        'status',
        'current_score',
        'joined_at',
        'left_at'
    ];

    protected $casts = [
        'room_id' => 'integer',
        'user_id' => 'integer',
        'current_score' => 'integer',
        'joined_at' => 'datetime',
        'left_at' => 'datetime',
    ];

    /**
     * 获取房间
     */
    public function room()
    {
        return $this->belongsTo(Room::class, 'room_id');
    }

    /**
     * 获取用户
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * 加入房间
     */
    public static function joinRoom($roomId, $userId)
    {
        // 检查是否已经在房间中
        $existing = static::where('room_id', $roomId)
            ->where('user_id', $userId)
            ->where('status', static::STATUS_ACTIVE)
            ->first();
            
        if ($existing) {
            return $existing;
        }
        
        // 创建新的房间用户关系
        $roomUser = new static();
        $roomUser->room_id = $roomId;
        $roomUser->user_id = $userId;
        $roomUser->status = static::STATUS_ACTIVE;
        $roomUser->current_score = 0;
        $roomUser->joined_at = Carbon::now();
        $roomUser->save();
        
        return $roomUser;
    }

    /**
     * 离开房间
     */
    public function leaveRoom()
    {
        $this->status = static::STATUS_LEFT;
        $this->left_at = Carbon::now();
        $this->save();
    }

    /**
     * 更新分数
     */
    public function updateScore($score)
    {
        $oldScore = $this->current_score;
        $this->current_score += $score;
        $this->save();
        
        error_log("RoomUser分数更新: user_id={$this->user_id}, room_id={$this->room_id}, old_score={$oldScore}, change={$score}, new_score={$this->current_score}");
    }
}
